import cv2
import numpy as np
from cap import VideoCapture

def detect_edges(image):
    """对图像进行边缘检测"""
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, threshold1=50, threshold2=150)
    kernel = np.ones((9, 9), np.uint8)
    edges = cv2.dilate(edges, kernel, iterations=1)  # 膨胀操作
    edges = cv2.erode(edges, kernel, iterations=1)   # 腐蚀操作

    return edges

def is_card_fully_detected(edges):
    """检测卡片的边缘是否完整进入视野"""
    # 查找轮廓
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 遍历所有轮廓，寻找最大的闭合轮廓
    for contour in contours:
        # 计算轮廓面积，筛选出较大的轮廓
        area = cv2.contourArea(contour)
        print(f"检测到轮廓: 面积={area}")
        if area > 3000:  # 根据卡片的大小可以调整这个阈值
            # 获取轮廓的边界框
            x, y, w, h = cv2.boundingRect(contour)
            
            # 判断卡片是否完全进入视野（例如卡片至少占用图像的一定比例）
            # 可以根据实际情况调整这个比例
            if w * h > 0.5 * edges.shape[0] * edges.shape[1]:
                return True
    return False

def capture_and_detect():
    # 打开摄像头
    cap = VideoCapture()

    # 捕获一帧图像
    frame = cap.read()

    if frame is None:
        print("无法读取图像")
        cap.release()
        return

    # 检测边缘
    edges = detect_edges(frame)

    # 检查卡片边缘是否完全进入视野
    if is_card_fully_detected(edges):
        print("卡片已完全进入视野！")
    else:
        print("卡片未完全进入视野！")

    # 保存原始图像和边缘图像
    cv2.imwrite("original_frame.jpg", frame)
    cv2.imwrite("edges_frame.jpg", edges)

    # 释放摄像头
    cap.release()

if __name__ == "__main__":
    capture_and_detect()
